package com.jt.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.*;

import javax.swing.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

@Configuration//标识配置类 一般与@Bean联用
@PropertySource("classpath:/properties/redis.properties")
public class RedisConfig {
    /**
     * redis单台测试
     */
    @Value("${redis.host}")
    private String host;
    @Value("${redis.port}")
    private Integer port;
    @Bean
    public Jedis jedis(){
        return new Jedis(host,port);
    }

    /**
     * 分片的jedis,是为了内存扩容,三倍的容量,三台当一台用
     * 采用一致性哈希算法,分配具体存储到哪台redis
     */
    /*@Value("${redis.nodes}")
    private String nodes;   //node,node,node
    @Bean
    public ShardedJedis shardedJedis(){
        List<JedisShardInfo> shards = new ArrayList<>();

        String[] nodeArray = nodes.split(",");
        for (String node:nodeArray){
            String host = node.split(":")[0];
            int port = Integer.parseInt(node.split(":")[1]);
            shards.add(new JedisShardInfo(host, port));
        }
        return new ShardedJedis(shards);
    }*/

    /**
     * 整合redis的哨兵机制
     */
    /*@Value("${redis.node}")
    private String node;
    @Bean
    public JedisSentinelPool jedisSentinelPool(){
        HashSet<String> sentinel = new HashSet<>();
        sentinel.add(node);
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(1000);
        poolConfig.setMaxIdle(60);
        poolConfig.setMinIdle(40);
        return new JedisSentinelPool("mymaster", sentinel,poolConfig);
    }*/

    /**
     * Redis集群
     */
    /*@Value("${redis.nodes}")
    private String nodes;//node,node,...
    @Bean
    public JedisCluster jedisCluster(){
        HashSet<HostAndPort> nodesSet = new HashSet<>();
        String[] nodeArray = nodes.split(",");
        for (String node:nodeArray){
            String host=node.split(":")[0];
            int port = Integer.parseInt(node.split(":")[1]);
            HostAndPort hostAndPort = new HostAndPort(host, port);
            nodesSet.add(hostAndPort);
        }
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(1000);
        config.setMaxIdle(60);
        config.setMinIdle(20);
        return new JedisCluster(nodesSet,config);
    }*/
}
